package engine.services.impl;

import java.net.HttpURLConnection;

import org.springframework.beans.factory.annotation.Autowired;

import engine.content.*;
import engine.services.IContentService;
import engine.services.IHttpConnectionService;


public class ContentService implements IContentService {
	@Autowired
	IHttpConnectionService httpConnectionService;
	
	ContentTypes attachmentType;


	public void setAttachmentType(ContentTypes attachmentType) {
		this.attachmentType = attachmentType;
	}


	private ContentService() {
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public IContent getResponse(String url) throws Exception {
		IContent content;
		Object urlContent;

		HttpURLConnection conn = httpConnectionService.openConnection(url);
		String contentType = conn.getHeaderField("Content-Type");
		String contentBase = conn.getHeaderField("Content-Base");
		if (contentType.contains("html")) {
			if (contentBase == null) {
				int lastSlash =url.lastIndexOf("/");
				if ( lastSlash > 6) {
					contentBase = url.substring(0, lastSlash);
				} else {
					contentBase = url;
				}
			}			
		}
		if (
				contentType.contains("html") ||
				contentType.contains("text") ||
				contentType.contains("xml") ||
				contentType.contains("txt")
			) 
		{
			String contentStr = httpConnectionService.getUrlContentString(conn);
			if (contentStr.indexOf("<rdf:RDF") > -1 || contentStr.indexOf("<rss") > -1) {
				content = new RSSContent();
			} else if (contentStr.startsWith("<?xml")) {
				content = new XMLContent();
			} else {
				content = new HtmlContent();
			}
			urlContent = contentStr;

		}
		else {
			
			urlContent = httpConnectionService.getURLContentForStream(url);
			content = new FileContent();
			if (attachmentType == ContentTypes.MEMORY) {
				content = new InMemoryContent();				
			} else {
				content = new FileContent();
			}
		}
		
		content.setContentType(contentType);
		content.setContentBase(contentBase);
		content.setContent(urlContent);
		httpConnectionService.closeConnection(conn);
		return content;
	}


	public void setHttpConnectionService(
			IHttpConnectionService httpConnectionService) {
		this.httpConnectionService = httpConnectionService;
	}
}
